<template>
  <div class="text-box">
    <!-- 日记弹出层头部导航栏 -->
      <NavTop>
        <template #left>
          <van-icon name="cross animate__animated animate__fadeInLeft" @click="backFn" />
        </template>
        <template #calendarbox2>
          <span>{{ userDiaryList.date }}</span>
          <p>{{ userDiaryList.week }}&nbsp; &nbsp;{{ userDiaryList.time }}</p>
        </template>
        <template #right>
          <van-icon name="success animate__animated animate__fadeInRight" @click="logFn" />
        </template>
      </NavTop>
    <van-form>
      <!-- 富文本编辑器 -->
      <quill-editor v-model="content" :options="editorOption" @change="onEditorChange($event)"> </quill-editor>
      <van-field name="uploader">
        <template #input>
          <van-uploader v-model="fileList" ref="uploader" accept=".png,.jpg,.jpeg" :before-read="beforeRead" :after-read="afterRead" :preview-full-image="false" multiple :max-count="3" />
        </template>
      </van-field>
      <!-- 日记天气/字数/地址详情 -->
      <div class="details">
        <!-- 天气 -->
        <span>
          <i :class="'qi-' + userDiaryList.nowicon"></i>
          <p>{{ userDiaryList.wearther }}&nbsp;·&nbsp;{{ userDiaryList.temperature }}℃</p>
        </span>
        <!-- 地址· -->
        <span>
          <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-dingwei"></use>
          </svg>
          <p>{{ userDiaryList.cityname }}</p>
        </span>
        <!-- 文字 -->
        <span>
          <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-zitiyulan"></use>
          </svg>
          <!-- <p>16 字</p> -->
          <p>{{ userDiaryList.tilength }} 字</p>
        </span>
      </div>
    </van-form>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import NavTop from '@/components/home/homenNavTop.vue'
import { updateDiaryApi } from '@/api/index'

import { Toast } from 'vant'
// import e from 'express'

// import BMap from 'bmap'

// 工具栏配置
const toolbarOptions = [
  // [{ list: 'bullet' }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  // [{ indent: '-1' }, { indent: '+1' }] // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
]

export default {
  components: {
    quillEditor,
    NavTop
  },
  data () {
    return {
      content: '', // 富文本编辑器默认内容
      editorOption: {
        //  富文本编辑器配置
        modules: {
          // 工具栏定义的
          toolbar: toolbarOptions,
          clipboard: {
            // 粘贴过滤
            matchers: [[Node.ELEMENT_NODE, this.HandleCustomMatcher]]
          }
        },
        // 主题
        theme: 'snow',
        placeholder: ' 时光荏苒 记录今日...'
      },
      // 上传图片
      fileList: [],
      // 压缩上传图片的base64
      imgurl: [],
      // 点击进来的用户日记数据
      userDiaryList: {}
    }
  },
  methods: {
    // 过滤 复制粘贴 的数据
    HandleCustomMatcher (node, Delta) {
      // 文字、图片等，从别处复制而来，清除自带样式，转为纯文本
      const ops = []
      Delta.ops.forEach((op) => {
        if (op.insert && typeof op.insert === 'string') {
          ops.push({
            insert: op.insert
          })
        }
      })
      Delta.ops = ops
      return Delta
    },
    // 返回
    backFn () {
      // this.$store.commit('setButtonShow', true)
      this.$router.replace('/userdiary')
    },
    // 提交 修改日记
    async logFn () {
      Toast.loading({
        message: '提交日记ing...',
        forbidClick: true,
        duration: 0
      })
      const arr1 = this.fileList.map(async (item, index) => {
        // 调用图片压缩处理函数 压缩图片
        const baseImg = await this.compressImg(this.fileList[index].content, 500, 0.7)
        // console.log(baseImg)
        return baseImg
      })
      const base64 = await Promise.all(arr1)
      this.imgurl = base64.join('||')
      try {
        const { data: res } = await updateDiaryApi(this.userDiaryList.id, this.userDiaryList.articleid, this.content, this.imgurl, this.userDiaryList.tilength)
        // console.log(res.status)
        if (res.status === 200) {
          Toast.clear()
          this.$router.replace('/home')
        }
      } catch (error) {
        // console.log('提交日记失败')
        Toast('提交日记失败')
      }
    },
    // 富文本内容改变事件
    onEditorChange (e) {
      // 计算 富文本内容 字数
      e.quill.deleteText(800, 4)
      // console.log(e)
      if (this.userDiaryList.content === '') {
        this.userDiaryList.tilength = 0
      } else {
        this.userDiaryList.tilength = e.quill.getLength() - 1
      }
      // this.content = e.text
      // console.log(this.content)
    },
    // 图片压缩处理函数
    compressImg (base64String, w, quality) {
      // 计算占多少 bytes
      function getBytesLength (str) {
        let num = str.length // 先用num保存一下字符串的长度（可以理解为：先假设每个字符都只占用一个字节）
        for (let i = 0; i < str.length; i++) {
          // 遍历字符串
          if (str.charCodeAt(i) > 255) {
            // 判断某个字符是否占用两个字节，如果是，num再+1
            num++
          }
        }
        return num // 返回最终的num，既是字符串总的字节长度
      }
      const base64Length = getBytesLength(base64String)
      // 计算占 多少 kb
      const size = base64Length / 1024

      // 判断图片是否小于 250kb  => 小于就不用压缩
      if (size < 200) {
        return base64String
      }
      // 判断图片 大于 250kb  => 压缩 图片
      const getMimeType = function (urlData) {
        const arr = urlData.split(',')
        const mime = arr[0].match(/:(.*?);/)[1]
        return mime
      }
      const newImage = new Image()
      let imgWidth, imgHeight

      const promise = new Promise((resolve) => (newImage.onload = resolve))
      newImage.src = base64String
      return promise.then(() => {
        imgWidth = newImage.width
        imgHeight = newImage.height
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        if (Math.max(imgWidth, imgHeight) > w) {
          if (imgWidth > imgHeight) {
            canvas.width = w
            canvas.height = (w * imgHeight) / imgWidth
          } else {
            canvas.height = w
            canvas.width = (w * imgWidth) / imgHeight
          }
        } else {
          canvas.width = imgWidth
          canvas.height = imgHeight
        }
        ctx.clearRect(0, 0, canvas.width, canvas.height)
        ctx.drawImage(newImage, 0, 0, canvas.width, canvas.height)
        const base64 = canvas.toDataURL(getMimeType(base64String), quality)
        // console.log(base64)
        return base64
      })
    },

    // 上传图片之前钩子
    beforeRead (file) {
      // console.log(this.fileList)
      // 一次上传单张, file 为对象 => 循环判断 file  是否为 合法格式图片
      if (!Array.isArray(file)) {
        if (!/(jpg|jpeg|png|JPG|PNG)/i.test(file.type)) {
          Toast('亲~只能上传jpg|jpeg|png|JPG|PNG图片格式噢')
          // console.log(file.type)
          return false
        }
        // console.log(file.content)
        // this.repeatImgs = 0
      } else {
        // 一次上传多张，file是一个数组 => 循环判断 file 数组 每一项 是否为 合法格式图片
        for (let i = 0; i < file.length; i++) {
          if (!/(jpg|jpeg|png|JPG|PNG)/i.test(file[i].type)) {
            Toast('亲~只能上传jpg|jpeg|png|JPG|PNG图片格式噢')
            // console.log(file.type)
            return false
          }
          // console.log(file[i])
        }
        // this.repeatImgs = 0
      }
      return true
    },
    // 上传图片成功的钩子
    async afterRead (file) {
      const arr1 = this.fileList.map(async (item, index) => {
        // console.log(this.fileList[index].content)
        // console.log();
        // 调用图片压缩处理函数 压缩图片
        const baseImg = await this.compressImg(this.fileList[index].content, 500, 0.7)
        // console.log(baseImg)
        return baseImg
      })
      const base64 = await Promise.all(arr1)
      this.imgurl = base64.join('||')
      // console.log(this.imgurl)
      // this.$store.commit('setArticleImg', this.imgurl)
      // console.log(this.fileList)
    },
    // 退出编辑清空日记数据
    emptyFn () {
      // console.log('清空日记数据')
      this.fileList = []
      this.imgurl = []
      // this.$store.commit('setArticleImg', this.imgurl)
      this.content = ''
    }
  },
  activated () {
    this.userDiaryList = this.$store.state.clickDiaryList
    // console.log(this.userDiaryList)
    this.content = this.userDiaryList.content
    // console.log(this.userDiaryList.imgurl === null)
    if (this.userDiaryList.imgurl === null) {
      this.fileList = []
      // console.log(this.fileList)
    } else {
      const arr = this.userDiaryList.imgurl.split('||')
      // console.log(arr)
      // this.fileList = arr
      // base64 编辑图片 回显
      this.fileList = arr.map((item) => ({ content: item }))
      // console.log(this.fileList)
    }
  }
  // updated () {
  //   this.$store.commit('setArticleData', [this.content, this.nowCityName, this.nowwearther, this.nowicon, this.temperature, this.TiLength])
  // }
}
</script>

<style lang="less" scoped>
/deep/.van-form{
  padding: 60px 0;
}
/deep/.calendarbox2 {
  padding: 10px !important;
  span {
    font-size: 16px !important;
  }
  p {
    font-size: 13px !important;
  }
}
/deep/.editor {
  line-height: normal !important;
  height: 500px;
}
/deep/.ql-editor {
  min-height: 220px;
  // max-height: 550px;
  padding: 0 28px;
}
/deep/.ql-toolbar.ql-snow {
  border: 0;
}
/deep/.ql-editor.ql-blank::before {
  color: #969799;
  font-style: normal;
  padding: 0 6px;
}
/deep/.ql-editor p {
  color: #646566;
  font-size: 14px;
  letter-spacing: 2px;
  line-height: 22px;
  // white-space: pre-wrap;
}
/deep/.ql-toolbar.ql-snow {
  border: 0;
}
/deep/.ql-container.ql-snow {
  border: 0;
}
/deep/.van-uploader__wrapper {
  padding-left: 12px;
}
/deep/.van-uploader__upload {
  width: 100px;
  height: 100px;
  border-radius: 10px;
  background-color: #ebedf0;
 /deep/.van-uploader__upload-icon {
    color: #6ed9a2 !important;
    font-size: 20px;
  }
}
/deep/.van-uploader__preview-image {
  border-radius: 10px;
  width: 100px;
  height: 100px;
}
/deep/.van-uploader__preview-delete {
  width: 18px;
  height: 18px;
  background-color: #f80000a6;
  border-radius: 50%;
}
/deep/.van-uploader__preview-delete-icon {
  top: -2px;
  right: -2px;
  font-size: 22px;
}
.details {
  padding: 5px 28px 20px 28px;

  span {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    padding: 10px 0;
    .van-loading {
      width: 20px;
      height: 20px;
    }

    i {
      font-size: 19px;
      color: #969799;
      padding-right: 6px;
    }
    .icon {
      width: 18px;
      height: 18px;
      padding-right: 6px;
      fill: #969799;
    }
    p {
      font-size: 12px;
      color: #969799;
    }
  }
}
.van-action-sheet__header {
  color: #969799;
}
// .content {
//   padding: 0 16px 80px;
//   display: flex;
//   flex-wrap: wrap;
//   justify-content: center;
//   span {
//     padding: 10px 26px;
//     display: flex;
//     flex-direction: column;
//     align-items: center;
//     .icon {
//       width: 32px;
//       height: 32px;
//     }
//     p {
//       font-size: 15px;
//       padding: 5px 0;
//       color: #969799;
//     }
//   }
// }
</style>
